/**
 * Copyright (c) 2019 AsHacker All rights reserved.
 * <p>
 * http://www.ashacker.com
 * <p>
 * 版权所有，侵权必究！
 */

package io.renren.modules.app.controller;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.exceptions.ClientException;
import io.renren.common.utils.R;
import io.renren.modules.app.utils.JwtUtils;
import io.renren.modules.lucky.entity.AppUserInfoEntity;
import io.renren.modules.lucky.service.AppUserInfoService;
import io.renren.modules.lucky.service.AppUserSmsService;
import io.renren.modules.lucky.service.AppWxUserService;
import io.renren.modules.sys.controller.AbstractController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 登录授权
 *
 * @author Chen chenchen@ashacker.com
 */
@RestController
@RequestMapping("/app")
@Api("登录接口")
public class AppLoginController extends AbstractController {

    @Autowired
    private AppUserSmsService appUserSmsService;

    @Autowired
    private AppUserInfoService appUserInfoService;

    @Autowired
    private AppWxUserService appWxUserService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 请求验证码
     */
    @PostMapping("validCode")
    @ApiOperation("请求验证码")
    public R validCode(@RequestParam String phone_num) {

        logger.info("validCode方法执行开始：传入参数为   " + phone_num);

        String phoneNum = phone_num == null ? "" : phone_num;

        // 插入数据信息
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            map = appUserSmsService.validCode(phoneNum);
        } catch (Exception e) {
            logger.error("保存信息失败,错误原因:" + e.getMessage(), e);
            e.printStackTrace();
        }

        logger.info("validCode方法执行结束：返回值为   " + JSON.toJSONString(map));

        return R.ok(map);
    }

    /**
     * 手机号码验证
     */
    @PostMapping("validPhone")
    @ApiOperation("手机号码验证")
    public R validPhone(@RequestParam String phone_num, @RequestParam String sms_code) {

        logger.info("validPhone方法执行开始：传入参数为   " + phone_num + "---" + sms_code);

        String phoneNum = phone_num == null ? "" : phone_num;
        String smsCode = sms_code == null ? "" : sms_code;

        // 表单校验
//		form.setUsername(req.getParameter("username"));
//		form.setPassword(req.getParameter("password"));
//		ValidatorUtils.validateEntity(form);

        // 用户登录
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            map = appUserInfoService.validPhone(phoneNum, smsCode);
        } catch (Exception e) {
            logger.error("保存信息失败,错误原因:" + e.getMessage(), e);
            e.printStackTrace();
        }
        logger.info("validPhone方法执行结束：返回值为   " + JSON.toJSONString(map));

        return R.ok(map);
    }

    /**
     * 微信绑定用户,目前以openId作为唯一标识，等后期多平台之后以unionId为唯一标识
     *
     * @return
     * @author HObOCat
     * @date 2019/11/7 13:57
     */
    @ApiOperation("微信绑定用户")
    @PostMapping("bindWechat")
    public R bindWechat(@RequestParam String phone_num, @RequestParam String sms_code, @RequestParam String open_id, @RequestParam(required = false) String union_id) {

        logger.info("bindWechat方法执行开始：传入参数为   " + phone_num + "---" + sms_code + "---" + open_id + "---" + union_id);

        String phoneNum = phone_num == null ? "" : phone_num;
        String smsCode = sms_code == null ? "" : sms_code;
        String openId = open_id == null ? "" : open_id;

        //校验手机号与验证码
        Map<String, Object> map = appUserSmsService.validPhoneWithSmscode(phoneNum, smsCode);

        if (map != null && map.size() > 0) {
            logger.info("userRegister方法执行结束：返回值为   " + JSON.toJSONString(map));
            return R.ok(map);
        }
        //用户是否有绑定信息
        Boolean bindFlag = appWxUserService.IsBindWechat(phoneNum);
        if (bindFlag) {
            map.put("ret", "4");
            map.put("info", "该号码已和别的微信用户绑定！");
            logger.info("userRegister方法执行结束：返回值为   " + JSON.toJSONString(map));
            return R.ok(map);
        }

        // 用户注册./登录
        AppUserInfoEntity infoEntity = appUserInfoService.queryOrRegistUserByPhoneNum(phoneNum);
        if (infoEntity == null) {
            map.put("ret", "5");
            map.put("info", "注册失败");
            logger.info("userRegister方法执行结束：返回值为   " + JSON.toJSONString(map));
            return R.ok(map);
        }

        //用户与微信进行绑定
        Boolean IsSuc = appWxUserService.bindWechatWithPhone(phoneNum, openId);
        if (!IsSuc) {
            map.put("ret", "6");
            map.put("info", "绑定失败");
            logger.info("userRegister方法执行结束：返回值为   " + JSON.toJSONString(map));
            return R.ok(map);
        }

        map.put("ret", "7");
        map.put("infoEntity", infoEntity);
        map.put("info", "绑定成功");

        // 生成token
        String token = jwtUtils.generateToken(infoEntity.getId());
        map.put("token", token);
        map.put("expire", jwtUtils.getExpire());

        logger.info("userRegister方法执行结束：返回值为   " + JSON.toJSONString(map));

        return R.ok(map);
    }

    /**
     * 用户注册
     */
    @PostMapping("userRegister")
    @ApiOperation("用户注册")
    public R userRegister(@RequestParam String phone_num, @RequestParam String user_pwd, @RequestParam String user_token,
                          @RequestParam String invite_code) {

        logger.info("userRegister方法执行开始：传入参数为   " + phone_num + "---" + user_pwd + "---" + user_token + "---" + invite_code);

        String userToken = user_token == null ? "" : user_token;
        String phoneNum = phone_num == null ? "" : phone_num;
        String userPwd = user_pwd == null ? "" : user_pwd;
        String inviteCode = invite_code == null ? "" : invite_code;

        Map<String, Object> map = new HashMap<String, Object>();

        // 用户登录
        AppUserInfoEntity infoEntity = appUserInfoService.register(phoneNum, userPwd, userToken, inviteCode);
        map.put("infoEntity", infoEntity);

        // 生成token
        String token = jwtUtils.generateToken(infoEntity.getId());
        map.put("expire", jwtUtils.getExpire());
        map.put("token", token);

        logger.info("userRegister方法执行结束：返回值为   " + JSON.toJSONString(map));

        return R.ok(map);
    }

    /**
     * 用户登录
     */
    @PostMapping("userLogin")
    @ApiOperation("用户登录")
    public R userLogin(@RequestParam String phone_num, @RequestParam String user_pwd) {

        logger.info("userLogin方法执行开始：传入参数为   " + phone_num + "---" + user_pwd);

        String phoneNum = phone_num == null ? "" : phone_num;
        String userPwd = user_pwd == null ? "" : user_pwd;

        Map<String, Object> map = new HashMap<String, Object>();

        // 用户登录
        AppUserInfoEntity infoEntity = appUserInfoService.login(phoneNum, userPwd);
        if (infoEntity != null) {
            map.put("infoEntity", infoEntity);

            // 生成token
            String token = jwtUtils.generateToken(infoEntity.getId());
            map.put("token", token);
            map.put("expire", jwtUtils.getExpire());
        } else {
            map.put("msg", "用户登录失败");
        }

        logger.info("userLogin方法执行结束：返回值为   " + JSON.toJSONString(map));

        return R.ok(map);
    }

}
